import { defineStore } from 'pinia'
import { store } from '/@/store'
import { MENUS_KEY, TOKEN_KEY, USER_INFO_KEY } from '/@/enums/cacheEnum'
import { getAuthCache, setAuthCache } from '/@/utils/auth'

import { LoginParam } from '@/api/sys/model/loginModel'
import { PageEnum } from '@/enums/pageEnum'
import { UserModel } from '@/api/sys/model/userModal'
import { login } from '@/api/sys/login'

interface UserState {
  userInfo: any
  count: number
  token?: string
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: null,
    count: 0,
    // token
    token: undefined,
  }),
  getters: {
    // 获取用户信息
    getUserInfo(): UserModel {
      return this.userInfo || getAuthCache<UserModel>(USER_INFO_KEY) || {}
    },
    // 获取token
    getToken(): string {
      return this.token || getAuthCache<string>(TOKEN_KEY)
    },
    // 是否登录
    isLogin(): boolean {
      return !!this.getToken
    },
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info || ''
      setAuthCache(TOKEN_KEY, info)
    },
    setUserInfo(info: UserModel | null) {
      this.userInfo = info
      setAuthCache(USER_INFO_KEY, info)
    },
    resetState() {
      this.userInfo = null
    },
    async login(params: LoginParam): Promise<UserModel | null> {
      try {
        const res = await login(params)
        const { data: result } = res
        if (result.code !== 200) {
          return Promise.reject(result)
        }
        this.setToken(result.data.loginCode)
        this.setUserInfo(result.data)
        return Promise.resolve(result.data)
        // return this.afterLoginAction()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // // 登录后的操作
    // async afterLoginAction(): Promise<any | null> {
    //   if (!this.getToken) return null
    //   // get user info
    //   const userInfo = await this.getUserInfoAction()
    //   // 做一些 特殊的登录操作
    //   return userInfo
    // },
    // // 获取用户信息
    // async getUserInfoAction(): Promise<any | null> {
    //   if (!this.getToken) return null
    //   const result = await getUserInfo()
    //   const { userInfo } = result.data
    //   this.setUserInfo(userInfo)
    //   return userInfo
    // },
    // 登出
    async logout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            this.setToken(undefined)
            this.setUserInfo(null)
            setAuthCache(MENUS_KEY, [])
            uni.reLaunch({ url: PageEnum.BASE_HOME })
          }
        },
      })
    },
    // 测试专用
    synIncrease() {
      this.count += 1
    },
    async asyncIncrease() {
      await new Promise((resolve) => setTimeout(resolve, 1000))
      this.count += 1
    },
  },
})

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store)
}
